<template>
  <div>
    <div class="search-hot">
      <div>热门搜索</div>
      <van-button
        class="search-hot-tag"
        v-for="item in searchHotList"
        :key="item.id"
        :text="item.first"
        @click="onTagClick(item.first)"
        size="small"
        round
      />
    </div>
    <van-cell-group>
      <van-cell
        v-for="(item, idx) in lastSearchList"
        :key="item"
        :title="item"
        @click="onTagClick(item)"
        icon="clock-o"
        center
      >
        <template #right-icon>
          <van-icon name="close" @click.stop="onRemoveLastSearchListItem(idx)" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import eventBus from '@/event-bus';
import * as tool from '@/utils';

export default {
  data () {
    return {
      // 最近搜索列表
      lastSearchList: JSON.parse(localStorage.getItem('lastSearchList')) || [],
    };
  },
  computed: {
    searchHotList () {
      return eventBus.searchHotList;
    },
  },
  created () {
    eventBus.$emit('updateSearchHotList');
  },
  methods: {
    onTagClick (v) {
      // 跳转至搜索结果页面
      this.$router.push({
        name: 'search-list',
        query: {
          searchValue: v,
        },
      });
      // 搜索最佳匹配
      eventBus.$emit('updateSearchMultimatch', v);
      // 获取搜索结果
      eventBus.$emit('updateSearchList', v);
      this.lastSearchList = tool.unique(this.lastSearchList.concat(v));
      // 存储最新数据
      this.saveLastSearchList();
    },
    // 删除最近搜索列表项
    onRemoveLastSearchListItem (idx) {
      this.lastSearchList.splice(idx, 1);
      // 存储最新数据
      this.saveLastSearchList();
    },
    // 存储最新数据
    saveLastSearchList () {
      localStorage.setItem('lastSearchList', JSON.stringify(this.lastSearchList));
    },
  },
}
</script>

<style scoped>
.search-hot>div {
  padding: 8px;
  font-size: 12px;
}
.search-hot-tag {
  margin-left: 16px;
  margin-bottom: 16px;
}
</style>